# coding: utf-8
from pathlib import Path
from typing import Union, List

from PySide6.QtCore import Qt
from PySide6.QtGui import QResizeEvent
from PySide6.QtWidgets import QFileDialog, QHBoxLayout
from qfluentwidgets import FluentIcon as FIF, TransparentPushButton, PrimaryPushButton, SimpleCardWidget, \
    VerticalSeparator

from common import SingleIcon
from components import ExpandCardWidget, ListWidget, BodyLabel, ElLineEdit, Alert
from .base import PluginBase


def get_file(folder: str):
    files = []
    for item in Path(folder).glob('*'):
        files.append(item)
    return files


def rename(infoList: List[dict]):
    for info in infoList:
        old: Path = info['old']
        completeNew: Path = info['completeNew']
        old.rename(completeNew)


class FileCardItem(SimpleCardWidget):
    def __init__(self, file: Union[str, Path], parent=None):
        super().__init__(parent)
        if isinstance(file, str):
            file = Path(file)
        self.file = file
        # 初始化组件
        self.horizontalLayout = QHBoxLayout(self)
        self.nameLabel = BodyLabel(file.name, self)
        self.typeLabel = BodyLabel(self)
        self.newLineEdit = ElLineEdit(self)
        if file.is_dir():
            self.typeLabel.setText('文件夹')
            self.suffixWidget = BodyLabel('/', self)
            self.suffixWidget.setAlignment(Qt.AlignmentFlag.AlignCenter)
        else:
            self.typeLabel.setText('文件')
            self.suffixWidget = ElLineEdit(self)
            self.suffixWidget.setText(file.suffix)
            self.suffixWidget.setPlaceholderText('后缀, 如:`.mp4`')
            self.suffixWidget.setClearButtonEnabled(True)
        # 设置组件布局
        self.horizontalLayout.setContentsMargins(16, 5, 16, 5)
        self.horizontalLayout.addWidget(self.nameLabel, 1, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(VerticalSeparator(self), 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.typeLabel, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.newLineEdit, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.suffixWidget, 0, Qt.AlignmentFlag.AlignRight)

        # 设置组件样式
        self.setFixedHeight(50)
        self.nameLabel.setMinimumWidth(200)
        self.typeLabel.setFixedWidth(80)
        self.newLineEdit.setFixedWidth(200)
        self.suffixWidget.setFixedWidth(150)

        self.typeLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.newLineEdit.setPlaceholderText('请输入新文件名')
        self.newLineEdit.setClearButtonEnabled(True)

    def getInfo(self):
        file = self.file
        new = self.newLineEdit.text()
        suffix = self.suffixWidget.text()
        completeNew = file.parent / f'{new}{suffix}'
        return {
            'old': file,
            'new': new,
            'suffix': suffix,
            'isFile': self.file.is_file(),
            'completeNew': completeNew
        }

    def resizeEvent(self, event: QResizeEvent):
        width = (event.size().width() - self.horizontalLayout.spacing() * 3) // 4
        self.nameLabel.setMaximumWidth(width)
        super().resizeEvent(event)


class FileRenameWidget(PluginBase):
    ICON = SingleIcon.RENAME
    NAME = '文件批量重命名'
    DESCRIPTION = '重命名文件或文件夹，支持批量重命名。'

    def __init__(self, parent=None):
        super().__init__(parent)
        self.cards = []  # type: List[FileCardItem]
        self.folderCard = ExpandCardWidget(FIF.FOLDER, '文件夹', self)
        self.cardList = ListWidget(self)
        self.startCard = ExpandCardWidget(FIF.PLAY_SOLID, '开始批量重命名', self)

        self.folderBtn = TransparentPushButton(FIF.FOLDER_ADD, '选择文件夹', self)
        self.startBtn = PrimaryPushButton(FIF.PLAY, '开始批量重命名', self)

        self.__initWidget()

    def __initWidget(self):
        self.folderCard.addWidget(self.folderBtn)
        self.startCard.addWidget(self.startBtn)

        self.addWidget(self.folderCard)
        self.addWidget(self.cardList, 1)
        self.addWidget(self.startCard)

        # 事件绑定
        self.folderBtn.clicked.connect(self.onSelectFolder)
        self.startBtn.clicked.connect(self.onStart)

    def onSelectFolder(self):
        folder = QFileDialog.getExistingDirectory(self, '选择文件夹', '', QFileDialog.Option.ShowDirsOnly)
        if not folder:
            return
        self.clear()

        self.folderBtn.setText(folder)
        self.toolTip.setTitle('获取文件')
        self.toolTip.setContent('正在获取文件信息')
        self.load(lambda: get_file(folder), slot=self.addRows)

    def addRows(self, files: Union[List[Path], Path]):
        if isinstance(files, Path):
            files = [files]
        for file in files:
            self.addRow(file)

    def addRow(self, file: Path):
        card = FileCardItem(file, self.cardList)
        self.cards.append(card)
        self.cardList.addWidget(card)

    def getInfos(self):
        infoList = []
        for item in self.cards:
            item: FileCardItem
            info = item.getInfo()
            if info['new']:
                infoList.append(info)
        return infoList

    def onStart(self):
        infoList = self.getInfos()
        if not infoList:
            Alert.warning('没有需要重命名的文件或文件夹')
            return
        self.toolTip.setTitle('重命名')
        self.toolTip.setContent('正在重命名文件，请稍后。。。')
        self.load(rename, infoList, slot=lambda: Alert.success(f'批量重命名成功，共{len(infoList)}个文件'))

    def clear(self):
        self.cardList.takeAll()
        self.cards.clear()
